package offer;

/**
 * @Author Elephas
 * @Date 2022/1/29
 **/
@FunctionalInterface
public interface IntToRoman {
    String intToRoman(int num);
}


class IntToRomanImpl1 implements IntToRoman{
    final static char ONE = 'I';
    final static char FIVE = 'V';
    final static char TEN = 'X';
    final static char FIFTY = 'L';
    final static char HUNDRED = 'C';
    final static char HALF_THOUSAND = 'D';
    final static char THOUSAND = 'M';
    @Override
    public String intToRoman(int num) {
        StringBuilder ans = new StringBuilder();
        while(num != 0){
            if(num > 1000){
                ans.append(THOUSAND);
                num -= 1000;
            }else if(num >= 900){
                ans.append(HUNDRED);
                ans.append(THOUSAND);
                num -= 900;
            }else if(num >= 500){
                ans.append(HALF_THOUSAND);
                num -= 500;
            }else if(num >= 400){
                ans.append(HUNDRED);
                ans.append(HALF_THOUSAND);
                num -= 400;
            }else if(num >= 100){
                ans.append(HUNDRED);
                num -= 100;
            }else if(num >= 90){
                ans.append(TEN);
                ans.append(HUNDRED);
                num -= 90;
            }else if(num >= 50){
                ans.append(FIFTY);
                num -= 50;
            }else if(num >= 40){
                ans.append(TEN);
                ans.append(FIFTY);
                num -= 40;
            }else if(num >= 10){
                ans.append(TEN);
                num -= 10;
            }else if(num >= 9){
                ans.append(ONE);
                ans.append(TEN);
                num -= 9;
            }else if(num >= 5){
                ans.append(FIVE);
                num -= 5;
            }else if(num >=4 ){
                ans.append(ONE);
                ans.append(FIVE);
                num -= 4;
            }else {
                ans.append(ONE);
                num -= 1;
            }
        }
        return ans.toString();
    }
}

/**
 * 官方题解，与Impl1逻辑相同，但是使用了数组，代码更加清晰
 */
class IntToRomanImpl2 implements IntToRoman{
    int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    public String intToRoman(int num) {
        StringBuffer roman = new StringBuffer();
        for (int i = 0; i < values.length; ++i) {
            int value = values[i];
            String symbol = symbols[i];
            while (num >= value) {
                num -= value;
                roman.append(symbol);
            }
            if (num == 0) {
                break;
            }
        }
        return roman.toString();
    }

}